package net.lzzy.service;

import net.lzzy.entity.Article;
import net.lzzy.repository.ArticleRepository;
import net.lzzy.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    //分页展示，用于前台展示文章
    public Page<Article> pageArticle(int page, int size){
        Pageable pageable = PageRequest.of(page, size);
        return articleRepository.findAll(pageable);
    }

    //根据ID查询，用于文章详情显示，使用redis缓存
    public Article findArticleById(Integer id){
        Object object = redisTemplate.opsForValue().get("article"+id);
        if (object != null) {
            return (Article)object;
        }
        else{
            Optional<Article> article= articleRepository.findById(id);
            if (article.isPresent()) {
                redisTemplate.opsForValue().set("article"+id, article.get());
                return article.get();
            }
            else {
                return null;
            }
        }
    }

    //查询所有文章，用于后台文章管理（后期可实现分页、排序等功能）
    public List<Article> findAll(){
        return articleRepository.findAll();
    }

    //根据ID删除文章,由于只设置了单向多对一，并设置了级联，直接调用删除评论的接口即可（级联只在设置的一侧有效，当使用文章删除方法时，由于外键约束导致失败）
    public void deleteById(Integer id){
        Article article = findArticleById(id);

        commentRepository.deleteByArticle(article);
        articleRepository.deleteById(id);
        redisTemplate.delete("article"+id);
    }

    //修改文章
    public void updateArticleById(Integer id, String title, String category, String content){
        Article article = findArticleById(id);
        article.setTitle(title);
        article.setCategory(category);
        article.setContent(content);
        articleRepository.save(article);
        redisTemplate.opsForValue().set("article"+id, article);
    }

    //新增文章
    public Article addArticle(String title, String category, String content){
        Article article = new Article();
        article.setTitle(title);
        article.setCategory(category);
        article.setContent(content);
        article.setDate(new Date());
        return articleRepository.save(article);
    }
}
